package com.doge.walknovel.widgets.imagecropper

import androidx.fragment.app.FragmentActivity
import java.io.File

object PickImageHelper {
    interface Callback {
        fun onResult(file: File)
    }

    private val listeners = mutableListOf<Callback>()

    fun registerCallback(callback: Callback) {
        if (!listeners.contains(callback)) listeners.add(callback)
    }

    fun unregisterCallback(callback: Callback) {
        if (listeners.contains(callback)) listeners.remove(callback)
    }

    fun get(
        type: Int,
        context: FragmentActivity,
        cropWidth: Int,
        cropHeight: Int
    ) {
        val tag = PickImageFragment::class.java.simpleName

        val fragmentManager = context.supportFragmentManager
        var fragment = fragmentManager.findFragmentByTag(tag) as? PickImageFragment
        if (fragment != null) {
            fragmentManager.beginTransaction()
                .remove(fragment)
                .commitAllowingStateLoss()
        }

        fragment = PickImageFragment.newInstance(type, cropWidth, cropHeight)
        fragmentManager.beginTransaction()
            .add(fragment, tag)
            .commitAllowingStateLoss()
    }

    fun dispatchResult(file: File) {
        listeners.toList().forEach { it.onResult(file) }
    }
}